package lex.lianliankan.ui;

import java.awt.BorderLayout;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.*;
import javax.swing.border.EmptyBorder;

import lex.lianliankan.GameModel;
import lex.lianliankan.utils.Images;

public class MainContentPane extends JPanel {
	private GameModel model = null;
	private GameView view = null;
	private JProgressBar progressBar = null;
	private JPanel progressPane = null;
	private Timer timer = null;

	public MainContentPane() {
		super();
		this.timer = new Timer(2000, new ActionListener() {
			private int elapsedTime = 0;

			public void actionPerformed(ActionEvent e) {
				if (elapsedTime++ < getProgressBar().getMaximum()) {
					getProgressBar().setValue(elapsedTime);
				} else {
					if (true == getModel().isFinished())
						this.message("��ϲ��!", "�����!");
					else
						this.message("���ϧ", "�Ͳ�һ�����~");
				}
			}

			private void message(String title, String message) {
				Window root = SwingUtilities.getWindowAncestor(MainContentPane.this);
				JOptionPane.showMessageDialog(root, message, title, JOptionPane.INFORMATION_MESSAGE);
			}
		});
		this.initialize();
	}

	public void start() {
		this.getModel().create();
		this.getView().repaint();
		this.timer.start();
	}

	public void hint() {

	}

	public void shuffle() {
		this.getModel().shuffle();
		this.getView().repaint();
	}

	public void pause() {

	}

	public GameModel getModel() {
		if (null == model) {
			model = new GameModel();
			model.create();
		}
		return this.model;
	}

	// ����GUI
	private void initialize() {
		this.setLayout(new BorderLayout());
		this.add(Box.createHorizontalStrut(11), BorderLayout.WEST);
		this.add(Box.createHorizontalStrut(12), BorderLayout.EAST);
		this.add(Box.createVerticalStrut(12), BorderLayout.SOUTH);
		this.add(this.getProgressPane(), BorderLayout.NORTH);
		this.add(this.getView(), BorderLayout.CENTER);
	}

	private GameView getView() {
		if (null == this.view) {
			view = new GameView(Images.getInstance());
			view.setModel(getModel());
		}
		return view;
	}

	private JPanel getProgressPane() {
		if (null == this.progressPane) {
			progressPane = new JPanel(new BorderLayout());
			progressPane.setBorder(new EmptyBorder(11, 11, 12, 12));
			progressPane.add(this.getProgressBar(), BorderLayout.CENTER);
		}
		return progressPane;
	}

	JProgressBar getProgressBar() {
		if (null == progressBar) {
			progressBar = new JProgressBar(0, 600);
			progressBar.setValue(0);
			progressBar.setStringPainted(true);
		}
		return progressBar;
	}
}
